package com.kehutong.crm.message.service;

import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;
import com.kehutong.common.enums.MessageBusinessEnum;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.crm.message.entity.MessageGlobalConfig;
import com.kehutong.crm.message.entity.MessageTemplateApp;

public class MessageAppService {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private MessageGlobalConfigService globalConfigService;

    public Object listPage(JSONObject jsonObject) {
        return Result.success(jdbcSession.findPage(MessageTemplateApp.class)
                                         .like(jsonObject, "name")
                                         .eq("deleted", false)
                                         .order("createTIme", "desc")
                                         .page(jsonObject)
                                         .exe());
    }

    public Object update(MessageTemplateApp app) {
        if (checkDuplicateByType(app.getId(), app.getTemplateType())) {
            return Result.error(0, "模板类型已存在");
        }

        // sync global config
        resetGlobalConfig(app.getId());
        syncGlobalConfig(app.getBusinessType(), app.getTemplateType(), app.getId());

        jdbcSession.updateById(app);
        return Result.success();
    }

    public Object save(MessageTemplateApp app) {
        if (checkDuplicateByType(app.getId(), app.getTemplateType())) {
            return Result.error(0, "模板类型已存在");
        }

        // sync global config
        resetGlobalConfig(app.getId());
        syncGlobalConfig(app.getBusinessType(), app.getTemplateType(), app.getId());

        jdbcSession.insert(app);

        return Result.success();
    }

    public Object delete(MessageTemplateApp app) {
        app.setDeleted(true);
        jdbcSession.updateById(app);

        return Result.success();
    }

    public void init(String tagString, String title, String content, TemplateType templateType, MessageBusinessEnum businessEnum){
        MessageTemplateApp template = jdbcSession.findOne(MessageTemplateApp.class)
                                                 .eq("templateType", templateType)
                                                 .eq("deleted", false)
                                                 .exe();

        if (Objects.isNull(template)) {
            template = Pool.newInstance(MessageTemplateApp.class);
            template.setTagArray(tagString);
            template.setBusinessType(businessEnum);
            template.setTemplateType(templateType);
            template.setTitle(title);
            template.setContent(content);
            jdbcSession.insert(template);
        } else {
            template.setTagArray(tagString);
            template.setBusinessType(businessEnum);
            template.setTemplateType(templateType);
            template.setTitle(title);
            template.setContent(content);
            jdbcSession.updateById(template);
        }

        // sync global config
        resetGlobalConfig(template.getId());
        syncGlobalConfig(template.getBusinessType(), template.getTemplateType(), template.getId());
    }

    private void resetGlobalConfig(String id){
        JSONObject json = new JSONObject();
        json.put("appTemplate", id);
        globalConfigService.listGlobalConfig(json).forEach(e -> {
            e.setAppTemplate(null);
            jdbcSession.updateById(e);
        });
    }
    private void syncGlobalConfig(MessageBusinessEnum businessState, TemplateType templateType, String id){
        MessageGlobalConfig globalConfig = globalConfigService.getGlobalConfig(templateType.getId());
        if (Objects.isNull(globalConfig)){
            globalConfig = Pool.newInstance(MessageGlobalConfig.class);
            globalConfig.setAppTemplate(id);
            globalConfig.setBusinessEnum(businessState);
            globalConfig.setTemplateEnum(templateType);
            globalConfigService.save(globalConfig);
        } else {
            globalConfig.setAppTemplate(id);
            globalConfig.setBusinessEnum(businessState);
            globalConfig.setTemplateEnum(templateType);
            globalConfigService.update(globalConfig);
        }
    }

    private boolean checkDuplicateByType(String id, TemplateType templateType){
        MessageTemplateApp template = jdbcSession.findOne(MessageTemplateApp.class)
                                              .eq("templateType", templateType)
                                              .eq("deleted", false)
                                              .exe();
        return Objects.nonNull(template) && !id.equals(template.getId());
    }

    private synchronized MessageTemplateApp getApp(TemplateType templateType){
        return jdbcSession.findOne(MessageTemplateApp.class)
                          .eq("templateType", templateType)
                          .eq("deleted", false)
                          .exe();
    }
    
}
